package com.xm.bluetoothkotlin.service

import android.app.*
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import com.xm.bluetoothkotlin.R

class BluetoothService(notification: Notification) : Service() {
    private var mNotification = notification
    private val manager by lazy { getSystemService(NOTIFICATION_SERVICE) as NotificationManager }
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startNotificationForeground()
        return START_STICKY
    }

    /**
     * 显示前台通知
     */
    private fun startNotificationForeground() {
        var notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            var channel =
                NotificationChannel("Bluetooth_id", "主服务", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true); //设置提示灯
            channel.lightColor = Color.RED; //设置提示灯颜色
            channel.setShowBadge(true); //显示logo
            channel.description = "bottombar notification"; //设置描述
            channel.lockscreenVisibility =
                Notification.VISIBILITY_PUBLIC; //设置锁屏可见 VISIBILITY_PUBLIC=可见
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
            Notification.Builder(this, "Bluetooth_id")
        } else {
            Notification.Builder(this)
        }

        //跨进程打开界面
        val intent = Intent().apply {
            action = "intent.action.main"
        }

        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        }else{
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
        }

        notification.setAutoCancel(false)
            .setContentTitle("蓝牙连接") //标题
            .setContentText("设备测量中") //内容
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_icon_bluetooth) //小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_icon_bluetooth))
            .setContentIntent(pendingIntent)
        startForeground(1, notification.build())
    }

    private fun stopForeGround() {
        manager.cancel(1)
        stopForeground(true)
    }

    override fun onDestroy() {
        stopForeGround()
        super.onDestroy()
    }
}